<template>
  <div>
    <div v-if="show">
      <el-cascader v-model="val" :options="options" @expand-change="exchange" @change="change" />
    </div>
  </div>
</template>
<script>
import { getTree } from '@/api/address'
import { notifyError } from '@/utils/message'
export default {
  props: {
    // eslint-disable-next-line vue/require-default-prop
    value: {
      type: [Array, Number]
    },
    show: {
      default: true,
      type: Boolean
    },
    placeholder: {
      default: null,
      type: String
    },
    type: {
      type: Number,
      default: 0
    },
    proviceData: {
      default() {
        return []
      },
      type: Array
    }
  },
  data() {
    return {
      changVal: [],
      areaId: 0,
      level: 1,
      // show: true,
      val: [], // v-model 的绑定
      // 返回地理位置
      options: []
    }
  },
  watch: {
    value: {
      handler(newVal, oldVal) {
        this.val = newVal
        this.show = true
        const that = this
        that.show = true
        // eslint-disable-next-line no-console
        console.log(`new: ${newVal}, old: ${oldVal}`)
      },
      deep: true
    }
  },
  mounted() {
    this.options = this.proviceData.map((item) => {
      const res = { value: item.id, label: item.name }
      if (this.type !== 1) {
        res.children = []
      }
      return res
    })
  },
  methods: {
    async getlist() {
      await getTree(this.areaId, this.type).then(data => {
        const res = data.data
        this.options.map((item) => {
          if (item.value === this.areaId) {
            item.children = res[0].children.map((item) => {
              const res = { label: item.name, value: item.id }
              if (item.children) {
                // 3级
                res.children = item.children.map((item) => ({ label: item.name, value: item.id }))
              }
              return res
            })
          }
        })
      })
    },
    // 修改事件
    change(e) {
      this.$emit('input', e)
    },
    exchange(e) {
      this.changVal = e
      if (e.length === 1) {
        this.areaId = e[0]
        this.getlist()
      }
    }
  }
}
</script>
